﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Quartz.Spi;
using SqlSugar;
using System.Diagnostics;
using System.Security.Claims;
using System.Security.Cryptography;
using Zhao.Common.EnumEntity;
using Zhao.Common.Helper;
using Zhao.IServer;
using Zhao.IServer.Log;
using Zhao.IServer.User;
using Zhao.Models.DTO;
using Zhao.Models.Entity;

namespace Zhao.Arena.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class BillController : ControllerBase
    {
        private readonly AesGcmHelper _aesGcmHelper;
        private readonly IBillServer _billServer;
        private readonly ILogsServer _logsServer;
        private readonly IAdminServer _adminServer;

        public BillController(AesGcmHelper aesGcmHelper, IBillServer billServer, ILogsServer logsServer, IAdminServer adminServer)
        {
            _aesGcmHelper = aesGcmHelper;
            _billServer = billServer;
            _logsServer = logsServer;
            _adminServer = adminServer;
        }

        /// <summary>
        /// 获取商户的账单
        /// </summary>
        /// <param name="searchaString"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{pageIndex:int}/{pageSize:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{tId:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{searchaString}")]
        [Route("{pageIndex:int}/{pageSize:int}/{tId:int}/{searchaString}")]
        public async Task<JsonResult> GetPageBill(int tId = 0, int pageIndex = 1, int pageSize = 10, string searchaString = " ")
        {
            var result = new ApiResult<PageModel<BillDto>>
            {
                Success = false,
                Message = "未查询到数据"
            };

            string? venueIdClaim = User.FindFirst("VenueId").Value;

            Guid.TryParse(venueIdClaim, out Guid venueId);

            //只获取对应球馆id的预约信息
            Expressionable<Bill, Venues> expressionable = new Expressionable<Bill, Venues>();

            if (venueId != default)
            {
                expressionable.And((a, b) => a.VenuesId.Equals(venueIdClaim));
            }
            //如果是管理员的话 就可能会查询相对应的球馆信息，进行一些数据核对
            else expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), (a, b) => b.VenueName.Contains(searchaString));

            expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), (a, b) => a.Remark.Contains(searchaString));

            expressionable.AndIF(tId != 0, (a, b) => a.Type == tId);

            result.Data = await _billServer.QueryPageBill(expressionable.ToExpression(), pageIndex, pageSize);

            if (result.Data != null)
            {
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);

        }


        /// <summary>
        /// 获取提现申请的 管理员审核提现
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("Review/{pageIndex:int}/{pageSize:int}")]
        [Route("Review/{pageIndex:int}/{pageSize:int}/{status:int}")]
        [Route("Review/{pageIndex:int}/{pageSize:int}/{searchaString}")]
        [Route("Review/{pageIndex:int}/{pageSize:int}/{status:int}/{searchaString}")]
        public async Task<JsonResult> GetAdminReview(int status = 0, int pageIndex = 1, int pageSize = 10, string searchaString = " ")
        {
            var result = new ApiResult<PageModel<BillDto>>
            {
                Success = false,
                Message = "未查询到数据"
            };

            string? roleId = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Role))?.Value;

            if (!(roleId == ((int)RoleEnum.FinanceAdmin).ToString()) || roleId.IsNullOrWhiteSpace())
            {
                result.Message = "无操作权限";
                result.Success = false;
                return new JsonResult(result);
            }

            //只获取对应球馆id的预约信息
            Expressionable<Bill, Venues> expressionable = new Expressionable<Bill, Venues>();

            //只查询提现的
            expressionable.And((a, b) => a.Type == 5);

            //如果是管理员的话 就可能会查询相对应的球馆信息，进行一些数据核对
            expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), (a, b) => b.VenueName.Contains(searchaString));

            expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), (a, b) => a.Remark.Contains(searchaString));

            expressionable.AndIF(status != 0, (a, b) => a.Status == status);

            result.Data = await _billServer.QueryPageBill(expressionable.ToExpression(), pageIndex, pageSize);

            if (result.Data != null)
            {
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);
        }


        /// <summary>
        /// 财务管理员审核
        /// </summary>
        /// <param name="billReview"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> BillReview([FromBody] BillReviewDto billReview)
        {
            var result = new ApiResult
            {
                Success = false,
                Message = "失败"
            };

            //必须是财务管理员才能进行审核
            string? roleId = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Role))?.Value;

            if (!(roleId == ((int)RoleEnum.FinanceAdmin).ToString()) || roleId.IsNullOrWhiteSpace())
            {
                result.Message = "无操作权限";
                return new JsonResult(result);
            }

            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;

            //获取到id
            if (idClaim.IsNullOrWhiteSpace())
            {
                result.Message = "编号无效";
                return new JsonResult(result);
            }

            int id = (int)idClaim.ToInt32();

            //去查询审核人信息以便记录日志
            var adminInfo = await _adminServer.QueryAsync(x => x.Id == id && x.Role == (int)RoleEnum.FinanceAdmin);

            //先查询订单是否存在
            var billInfo = await _billServer.QueryAsync(x => x.Id == billReview.Id);

            if (billInfo == null)
            {
                result.Message = "查询不到订单号";
                return new JsonResult(result);
            }

            if (billInfo.Type != 5)
            {
                result.Message = "该订单无需审核";
                return new JsonResult(result);
            }

            if (billReview.Status == 1)
            {
                if (billReview.OrderNumber.IsNullOrWhiteSpace())
                {
                    result.Message = "转账订单号不能为空";
                    return new JsonResult(result);
                }
            }

            bool isWin = await _billServer.Review(billReview);

            if (isWin)
            {
                result.Success = true;
                result.Message = "成功";
                await _logsServer.Info($"提现审核,审核人id{adminInfo.Id},审核人名称{adminInfo.FName},审核订单{billInfo.Id},订单金额{billInfo.Amount},审核状态{billInfo.Status},审核成功");
            }
            else { await _logsServer.Info($"提现审核,审核人id{adminInfo.Id},审核人名称{adminInfo.FName},审核订单{billInfo.Id},订单金额{billInfo.Amount},审核状态{billInfo.Status},审核失败"); }


            return new JsonResult(result);
        }
    }
}
